package com.appleframework.core;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class BaseDao<E> extends JdbcDaoSupport
{

    private static final Logger log = Logger.getLogger(BaseDao.class);

    /**
     * 添加 ，属性和数据库字段名一致，返回主键
     * 
     * @param objForSave ,继承Saveable 的接口的类
     * @return
     */
    public Number saveAndReturnKey(Saveable objForSave)
    {
        return saveAndReturnKey(objForSave, objForSave.getTableName(), objForSave.getKeyColumns());
    }

    /**
     * 添加实体,返回主键
     * 
     * @param objForSave
     * @param tableName
     * @param columnAndValue
     * @param keyColumns
     * @return
     */
    public Number saveAndReturnKey(Object objForSave, String tableName, String... keyColumns)
    {
        SimpleJdbcInsert insertActor = getSimpleJdbcInsert();
        insertActor.setTableName(tableName);
        insertActor.usingGeneratedKeyColumns(keyColumns);
        Number newId = insertActor.executeAndReturnKey(new BeanPropertySqlParameterSource(objForSave));
        traceSql(insertActor.getInsertString());
        return newId;
    }

    /**
     * @param objForSave 插入数据库的类
     * @param tableName
     * @param keyColumns
     * @return
     */
    public void save(Saveable objForSave)
    {
        SimpleJdbcInsert insertActor = getSimpleJdbcInsert();
        insertActor.setTableName(objForSave.getTableName());
        insertActor.execute(new BeanPropertySqlParameterSource(objForSave));
        traceSql(insertActor.getInsertString());
    }

    /**
     * @param objForSave 插入数据库的类，注意
     * @param tableName
     * @param keyColumns
     * @return
     */
    public void save(Object objForSave, String tableName)
    {
        SimpleJdbcInsert insertActor = getSimpleJdbcInsert();
        insertActor.setTableName(tableName);
        insertActor.execute(new BeanPropertySqlParameterSource(objForSave));
        traceSql(insertActor.getInsertString());
    }

    /**
     * 
     * @param objForSave 插入数据库的类
     * @param tableName
     * @param keyColumns
     * @return
     */
    public void save(Object objForSave, String tableName, String... keyColumns)
    {
        SimpleJdbcInsert insertActor = getSimpleJdbcInsert();
        insertActor.setTableName(tableName);
        insertActor.execute(new BeanPropertySqlParameterSource(objForSave));
        traceSql(insertActor.getInsertString());
    }

    /**
     * 
     * @param objForSave
     * @param tableName
     * @param columnAndValue
     * @param keyColumns
     * @return
     */
    public Number saveAndReturnKey(String tableName, Map<String, Object> columnAndValue, String... keyColumns)
    {
        SimpleJdbcInsert insertActor = getSimpleJdbcInsert();
        insertActor.setTableName(tableName);
        insertActor.usingGeneratedKeyColumns(keyColumns);
        Number newId = insertActor.executeAndReturnKey(columnAndValue);
        traceSql(insertActor.getInsertString());
        return newId;
    }

    // ----tools
    public SimpleJdbcInsert getSimpleJdbcInsert()
    {
        return new SimpleJdbcInsert(getJdbcTemplate());
    }

    public SimpleJdbcInsert getSimpleJdbcInsert(String tableName)
    {
        return new SimpleJdbcInsert(getJdbcTemplate());
    }

    /**
     * <一句话功能简述> 共公分页性能，性能不会很好，如果太慢，需要客制化分页sql <功能详细描述>
     * 
     * @param sql [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public Page<E> getPage(Page<E> page, String sqlQuery)
    {
        // 当前第几页
        int pageNo = page.getPageNo();
        // 每页的大小
        int pageSize = page.getPageSize();

        List<E> objs = (List<E>) getJdbcTemplate().queryForList(
                sqlQuery + " limit " + (page.getPageNo() - 1) + "," + page.getPageSize());

        int totalCount =getAllResult(sqlQuery);

        page.setResult(objs);
        page.setTotalCount(totalCount);

        return page;
    }

    /**
     * <一句话功能简述> 返回总页数 <功能详细描述>
     * 
     * @param sql [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public int getAllResult(String sqlQuery)
    {
        // 总记录数
        String preQuery = "select count(*) ";
        if (sqlQuery != null && !"".equals(sqlQuery))
        {
            if (sqlQuery.toUpperCase().indexOf("FROM") > 0)
            {
                sqlQuery = preQuery + sqlQuery.substring(sqlQuery.toUpperCase().indexOf("FROM"));
            }
        }
        int total = getJdbcTemplate().queryForInt(sqlQuery);

        return total;
    }

    public void traceSql(String sql)
    {
        log.info("JDBC:" + sql);
    }

    public static void main(String[] args)
    {
        String sqlQuery = "select * from xx ,aa where xx.id = aa.id";
        String preQuery = "select count(*) ";

    }
}
